;; LaTeX 环境配置

(require 'init-package)

(when (maybe-require-package 'auctex)
  (progn
    (require-package 'auctex-latexmk)
    (require-package 'cdlatex)

    (add-hook 'tex-mode-hook 'my-latex-setup)
    (add-hook 'TeX-mode-hook 'my-latex-setup)
    ))

(defun my-latex-setup ()
  (turn-on-cdlatex)
  ;;(turn-on-auto-fill)
  (set-fill-column 78)
  (auto-fill-mode t)

  (require 'init-outline-setup)         ;outline-minor-mode 快捷键绑定
  (outline-minor-mode t)

  (setq-default TeX-master nil)
  (setq tab-width 2
        LaTeX-item-indent 0
        LaTeX-indent-level 2

        TeX-auto-save t
        TeX-parse-self t
        ;;TeX-electric-escape t           ; 输入\时跳转到minibuf
        )

  ;; 设置默认使用 xelatex 编译，并且生成 synctex 文件
  ;; synctex 文件用于反向搜索
  (add-to-list 'TeX-command-list
               '("XeLaTeX" "%`xelatex -synctex=1 %(mode)%' %T" TeX-run-TeX nil t))

  ;; auctex-latexmk
  ;; latexmk 需要 ~/.latexmkrc 文件配合，在 ~/.emacs.d 下有备份
  ;; 建议将 .latexmkrc 文件放到主tex文件同目录下
  (when (maybe-require-package 'auctex-latexmk)
    (auctex-latexmk-setup)
    (setq auctex-latexmk-inherit-TeX-PDF-mode t))

  ;; 设备默认编译命令
  (setq TeX-command-default "LatexMk")

  ;; 设置源文件与PDF正反向搜索
  (setq TeX-PDF-mode t
        TeX-source-correlate-mode t
        TeX-source-correlate-method 'synctex
        ;;TeX-source-correlate-start-server t
        TeX-view-program-list '(("Sumatra PDF"
                                 ("SumatraPDF.exe -reuse-instance"
                                  (mode-io-correlate " -forward-search %b %n ")
                                  " %o")))
        )

  ;; 在SumatraPDF设置中输入下面这行，注意改路径
  ;; "D:\tools\msys64\ucrt64\bin\emacsclientw.exe" -n +%l "%f"
  (eval-after-load 'tex
    '(progn
       (assq-delete-all 'output-pdf TeX-view-program-selection)
       (add-to-list 'TeX-view-program-selection '(output-pdf "Sumatra PDF"))))
  )

(provide 'init-latex)
